function solveNQueens(n)
    local board = {} -- 初始化一个空棋盘
    for i = 1, n do
        board[i] = {}
        for j = 1, n do
            board[i][j] = false -- 初始状态下，每个格子都没有皇后
        end
    end

    local solutions = {} -- 存放所有解的容器

    local function backtrack(row)
        if row > n then -- 如果已经放置了 N 个皇后，找到一个解
            local solutionStr = ""
            for r = 1, n do
                for c = 1, n do
                    solutionStr = solutionStr .. (board[r][c] and "Q " or ". ")
                end
                solutionStr = solutionStr .. "\n"
            end
            table.insert(solutions, solutionStr)
            return
        end

        for col = 1, n do -- 依次尝试在当前行的每个列放置皇后
            if isSafe(row, col, board) then
                board[row][col] = true -- 放置皇后
                backtrack(row + 1) -- 继续在下一行放置皇后
                board[row][col] = false -- 回溯：撤销当前行的皇后放置
            end
        end
    end

    function isSafe(row, col, board)
        -- 检查当前列是否有皇后
        for r = 1, row - 1 do
            if board[r][col] then
                return false
            end
        end

        -- 检查左上到右下的对角线是否有皇后
        local leftUpDiag = col - row + 1
        for r = 1, row - 1 do
            local c = leftUpDiag + r
            if c <= n and board[r][c] then
                return false
            end
        end

        -- 检查右上到左下的对角线是否有皇后
        local rightUpDiag = col + row - 1
        for r = 1, row - 1 do
            local c = rightUpDiag - r
            if c >= 1 and board[r][c] then
                return false
            end
        end

        return true -- 当前位置可以安全放置皇后
    end

    backtrack(1) -- 从第一行开始放置皇后

    return solutions
end

-- 示例：求解 4 皇后问题
local solutions = solveNQueens(4)
for _, solution in ipairs(solutions) do
    print(solution)
end